package com.example.uniappspringbootstartweb.Util;

/**
 * Created by lilijava
 * on 2025/1/1
 * <p>
 * on  uni-app-springboot-start-web
 */
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class ShuffleUtil {

    /**
     * 使用 Fisher-Yates 算法打乱列表中的元素顺序。
     *
     * @param list 要打乱顺序的列表
     * @param <T>  列表中元素的类型
     * @return 打乱顺序后的新列表
     */
    public static <T> List<T> shuffleList(List<T> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }

        List<T> shuffledList = new ArrayList<>(list);
        Random rng = new Random();
        for (int i = shuffledList.size() - 1; i > 0; i--) {
            int j = rng.nextInt(i + 1);
            // 交换元素 i 和 j
            T temp = shuffledList.get(i);
            shuffledList.set(i, shuffledList.get(j));
            shuffledList.set(j, temp);
        }
        return shuffledList;
    }
}